package com.sgb.kjwl.view.ui.adapter.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.util.Pair;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderForCompanyActivity;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.BiddingOrderDetailsActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.util.List;

/**
 * Describe:    报价单位——其他人视角适配器
 * Author:  yangLei
 * Date:    2021/4/15
 */
public class OfferOwnerAdapter2 extends BaseRecycleAdapter<OrderQuoteEntity> {

    private OnTabClickListener onTabClickListener;
    private Context context;
    private boolean isBidding;

    public OfferOwnerAdapter2(Context context, List<OrderQuoteEntity> data, boolean isBidding) {
        super(context, R.layout.item_offer_owner_map_list, data);
        this.context = context;
        this.isBidding = isBidding;
    }

    public interface OnTabClickListener {
        void onAgreeClick(OrderQuoteEntity entity);

        void onChat(String account);

    }

    public void setOnTabClickListener(OnTabClickListener onTabClickListener) {
        this.onTabClickListener = onTabClickListener;
    }

    @Override
    public void convert(ItemViewHolder holder, OrderQuoteEntity entity) {
        TextView owner_name = holder.getItem().findViewById(R.id.owner_name);
        TextView freight_offer = holder.getItem().findViewById(R.id.freight_offer);
        ImageView car_iv = holder.getItem().findViewById(R.id.car_iv);
        TextView car_info = holder.getItem().findViewById(R.id.car_info);
        TextView position_info = holder.getItem().findViewById(R.id.position_info);
        TextView loading_distance = holder.getItem().findViewById(R.id.loading_distance);
        LinearLayout distance_bar = holder.getItem().findViewById(R.id.distance_bar);
        TextView offer_status = holder.getItem().findViewById(R.id.offer_status);
        TextView view_order = holder.getItem().findViewById(R.id.view_order);
        TextView right_btn = holder.getItem().findViewById(R.id.right_btn);
        TextView address_hint = holder.getItem().findViewById(R.id.address_hint);
        LinearLayout exchange_tab = holder.getItem().findViewById(R.id.exchange_tab);
        LinearLayout call_phone_tab = holder.getItem().findViewById(R.id.call_phone_tab);
        LinearLayout handle_layout = holder.getItem().findViewById(R.id.handle_layout);
        LinearLayout car_info_layout = holder.getItem().findViewById(R.id.car_info_layout);
        View line_view = holder.getItem().findViewById(R.id.line_view);

        /*运费报价*/
        if (isBidding) {
            if (!TextUtils.isEmpty(entity.getFreight())) {
                freight_offer.setText(NumberUtil.trim0(entity.getFreight()) + "元/吨");

            } else {
                freight_offer.setText("/");
            }
        } else {
            if (!TextUtils.isEmpty(entity.getAllFreight())) {
                freight_offer.setText(NumberUtil.trim0(entity.getAllFreight()) + "元");
            } else {
                freight_offer.setText("/");
            }
        }

        /*距离*/
        double distance = 0.0d;
        if (!TextUtils.isEmpty(entity.getDistance())) {
            distance = Double.parseDouble(entity.getDistance());
        } else if (entity.getLongitude() != null && entity.getLongitude() > 0
                && entity.getLatitude() != null && entity.getLatitude() > 0) {
            distance = LonLatUtils.getDistance(entity.getLongitude(), entity.getLatitude(),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, ""))
            );
        }
        if (distance <= 0) {
            loading_distance.setText("");
            distance_bar.setVisibility(View.GONE);
        } else {
            loading_distance.setText("距装货地 " + (distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km"));
            distance_bar.setVisibility(View.VISIBLE);
        }

        exchange_tab.setOnClickListener(v -> {
            if (isLogin()) {
                if (entity != null && !TextUtils.isEmpty(entity.getImAccount())) {
                    if (onTabClickListener != null) {
                        onTabClickListener.onChat(entity.getImAccount());
                    }
                }
            } else {
                VerificationCodeLoginActivity.start(context);
            }
        });
        call_phone_tab.setOnClickListener(v -> checkCanCall(entity));
        view_order.setOnClickListener(v -> viewOrder(entity));
        right_btn.setOnClickListener(v -> clickRightBtn(entity));

        handle_layout.setVisibility(View.GONE);
        line_view.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(entity.getIsSelfOffer()) && entity.getIsSelfOffer().equals("1")) {//是自己报的价
//            普通货源——1 已报价 2 待支付(已同意) 3 已支付 4 超时未支付 5 已失效 / 货主未同意
//            竞价货源——1 已报价 2 已同意 5 货主未同意
            switch (entity.getOfferStatus()) {
                //已同意
                case "2":
                    if (isBidding) {
                        view_order.setVisibility(View.VISIBLE);
                        right_btn.setVisibility(View.GONE);
                        offer_status.setText("报价已同意");
                        offer_status.setTextColor(Color.parseColor("#06C764"));
                    } else {
                        view_order.setVisibility(View.GONE);
                        right_btn.setVisibility(View.VISIBLE);
                        right_btn.setText("支付信息费");
                        offer_status.setText("报价待支付");
                        offer_status.setTextColor(Color.parseColor("#FFC000"));
                    }
                    handle_layout.setVisibility(View.VISIBLE);
                    line_view.setVisibility(View.VISIBLE);
                    break;

                case "3":
                    if (!isBidding) {
                        view_order.setVisibility(View.VISIBLE);
                        right_btn.setVisibility(View.GONE);
                        offer_status.setText("报价已支付");
                        offer_status.setTextColor(Color.parseColor("#06C764"));
                        handle_layout.setVisibility(View.VISIBLE);
                        line_view.setVisibility(View.VISIBLE);
                    }
                    break;

                //未同意、失效
                case "5":
                    if (isBidding) {
                        offer_status.setText("报价未同意");
                        offer_status.setTextColor(Color.parseColor("#FFC000"));
                    } else {
                        offer_status.setText("");//已失效状态不展示
                        offer_status.setTextColor(Color.parseColor("#C0C4CC"));
                    }
                    break;

                //待确认
                case "1":
                default:
                    offer_status.setText("");
                    break;
            }
        }

        String offerType = entity.getOfferType();
        String title = "";
        String address = "";
        switch (offerType) {
            case "1"://企业
                address_hint.setText("地址");
                car_info_layout.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(entity.getCompanyTeamAddress())) {
                    address = entity.getCompanyTeamAddress();
                }
                if (!TextUtils.isEmpty(entity.getCompanyNo())
                        && !TextUtils.isEmpty(UserOperating.getInstance().getTeamOrCompanyNameNo())
                        && entity.getCompanyNo().equals(UserOperating.getInstance().getTeamOrCompanyNameNo())) {
                    title = !TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "/";
                    offer_status.setVisibility(View.VISIBLE);
                } else {
                    title = !TextUtils.isEmpty(entity.getCompanyName()) ? replaceString2Star(entity.getCompanyName(), 2, 0) : "/";
                    offer_status.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(entity.getOfferStatus()) && entity.getOfferStatus().equals("2")) {
                    car_iv.setImageResource(R.mipmap.icon_marker_offer_company_yellow);
                } else if (!TextUtils.isEmpty(entity.getSourceFreight()) && !TextUtils.isEmpty(entity.getFreight())) {
                    car_iv.setImageResource(Double.parseDouble(entity.getFreight()) > Double.parseDouble(entity.getSourceFreight())
                            ? R.mipmap.icon_marker_offer_company_red : R.mipmap.icon_marker_offer_company_green);
                } else {
                    car_iv.setImageResource(R.mipmap.icon_marker_offer_company_red);
                }
                break;

            case "2"://团队
                address_hint.setText("团队地址");
                car_info_layout.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(entity.getCompanyTeamAddress())) {
                    address = entity.getCompanyTeamAddress();
                }
                if (!TextUtils.isEmpty(entity.getTeamNo())
                        && !TextUtils.isEmpty(UserOperating.getInstance().getTeamOrCompanyNameNo())
                        && entity.getTeamNo().equals(UserOperating.getInstance().getTeamOrCompanyNameNo())) {
                    title = !TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "/";
                    offer_status.setVisibility(View.VISIBLE);
                } else {
                    title = !TextUtils.isEmpty(entity.getTeamName()) ? replaceString2Star(entity.getTeamName(), 2, 0) : "/";
                    offer_status.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(entity.getOfferStatus()) && entity.getOfferStatus().equals("2")) {
                    car_iv.setImageResource(R.mipmap.icon_marker_offer_team_yellow);
                } else if (!TextUtils.isEmpty(entity.getSourceFreight()) && !TextUtils.isEmpty(entity.getFreight())) {
                    car_iv.setImageResource(Double.parseDouble(entity.getFreight()) > Double.parseDouble(entity.getSourceFreight())
                            ? R.mipmap.icon_marker_offer_team_red : R.mipmap.icon_marker_offer_team_green);
                } else {
                    car_iv.setImageResource(R.mipmap.icon_marker_offer_team_red);
                }
                break;

            case "3"://个人
                address_hint.setText("车辆位置");
                if (!TextUtils.isEmpty(entity.getDetailAddress())) {
                    address = entity.getDetailAddress();
                }
                String carInfo = "";
                if (!TextUtils.isEmpty(entity.getCarTypeName()))
                    carInfo += entity.getCarTypeName() + " ";
                if (!TextUtils.isEmpty(entity.getCarLenName()))
                    carInfo += "车长" + entity.getCarLenName() + " ";
                if (!TextUtils.isEmpty(entity.getHeightHurdle()))
                    carInfo += "栏高" + NumberUtil.trim0(entity.getHeightHurdle()) + "米 ";
                car_info.setText(TextUtils.isEmpty(carInfo) ? "/" : carInfo);
                car_info_layout.setVisibility(View.VISIBLE);

                if (!TextUtils.isEmpty(UserOperating.getInstance().getUserNo())
                        && !TextUtils.isEmpty(entity.getUserNo())
                        && UserOperating.getInstance().getUserNo().equals(entity.getUserNo())) {
                    title = !TextUtils.isEmpty(entity.getCarNumber()) ? entity.getCarNumber() : "/";
                    offer_status.setVisibility(View.VISIBLE);
                } else {
                    title = !TextUtils.isEmpty(entity.getCarNumber()) ? replaceString2Star(entity.getCarNumber(), 2, 0) : "/";
                    offer_status.setVisibility(View.GONE);
                }

                if (isBidding) {
                    if (!TextUtils.isEmpty(entity.getOfferStatus()) && entity.getOfferStatus().equals("2")) {
                        car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_yellow);
                    } else if (!TextUtils.isEmpty(entity.getFreightType())) {
                        if (entity.getFreightType().equals("1")) {
                            car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_red);
                        } else if (!TextUtils.isEmpty(entity.getSourceAllFreight()) && !TextUtils.isEmpty(entity.getAllFreight())) {
                            car_iv.setImageResource(Double.parseDouble(entity.getAllFreight()) > Double.parseDouble(entity.getSourceAllFreight())
                                    ? R.mipmap.icon_marker_offer_personal_red : R.mipmap.icon_marker_offer_personal_green);
                        } else {
                            car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_red);
                        }
                    }
                } else {
                    if (!TextUtils.isEmpty(entity.getFreightType())) {
                        if (entity.getFreightType().equals("1")) {
                            car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_red);
                        } else {
                            if (!TextUtils.isEmpty(entity.getOfferStatus()) && entity.getOfferStatus().equals("2")) {
                                car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_yellow);
                            } else if (!TextUtils.isEmpty(entity.getSourceAllFreight()) && !TextUtils.isEmpty(entity.getAllFreight())) {
                                car_iv.setImageResource(Double.parseDouble(entity.getAllFreight()) > Double.parseDouble(entity.getSourceAllFreight())
                                        ? R.mipmap.icon_marker_offer_personal_red : R.mipmap.icon_marker_offer_personal_green);
                            } else {
                                car_iv.setImageResource(R.mipmap.icon_marker_offer_personal_red);
                            }
                        }
                    }
                }
                break;
        }
        owner_name.setText(!TextUtils.isEmpty(title) ? title : "/");
        position_info.setText(!TextUtils.isEmpty(address) ? address : "/");
    }

    /**
     * 查看订单
     *
     * @param entity
     */
    private void viewOrder(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOfferStatus())) {
            if (isBidding) {
                if (entity.getOfferStatus().equals("2")) {
                    //查看竞价订单
                    skipBiddingOrder(entity);
                }
            } else {
                if (entity.getOfferStatus().equals("3")) {
                    //已支付，查看货运订单
                    skipTransportOrder(entity);
                }
            }
        }
    }

    /**
     * 支付信息费
     *
     * @param entity
     */
    private void clickRightBtn(OrderQuoteEntity entity) {
        if (!isBidding && !TextUtils.isEmpty(entity.getOfferStatus())) {
            if (entity.getOfferStatus().equals("2")) {
                payMessageSure(entity);
            }
        }
    }

    /**
     * 支付信息费，确认接单
     *
     * @param entity
     */
    private void payMessageSure(OrderQuoteEntity entity) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setGoodsSourceNo(entity.getSourceNo());
        orderEntity.setCarNumber(entity.getCarNumber());
        orderEntity.setHeightHurdle(entity.getHeightHurdle());
        orderEntity.setWeight(entity.getWeight());
        orderEntity.setCarLen(entity.getCarLenName());
        orderEntity.setCarType(entity.getCarTypeName());
        orderEntity.setCityName(entity.getCityName());
        orderEntity.setProvinceName(entity.getProvinceName());
        orderEntity.setDistrictName(entity.getDistrictName());
        orderEntity.setDetailAddress(entity.getDetailAddress());
        orderEntity.setDriverNo(entity.getDriverNo());
        orderEntity.setCarOfferNo(entity.getCarOfferNo());
        orderEntity.setGoodsOfferNo(entity.getGoodsOfferNo());
        orderEntity.setNote(entity.getNote());
        orderEntity.setDiyField(entity.getDiyField());
        orderEntity.setQuotation(true);
        orderEntity.setIsDump(entity.getIsDump());
        orderEntity.setInTime(entity.getInTime());
        if (!UserOperating.getInstance().isPersonal()) {
            PayQuotationOrderForCompanyActivity.start(context, entity.getGoodsOfferNo());
        } else {
            PayQuotationOrderActivity.start(context, entity.getGoodsOfferNo());
        }
    }

    /**
     * 跳转货运订单详情
     *
     * @param entity
     */
    private void skipTransportOrder(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOrderNo())) {
            ActivityJump.jumpToActivity(context, TransportOrderDetailOwnerActivity.class, Pair.create("no", entity.getOrderNo()),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
        }
    }

    /**
     * 跳转竞价订单详情
     *
     * @param entity
     */
    private void skipBiddingOrder(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOrderNo())) {
            //跳转竞价订单详情（该页面进入的都不是货主身份）
            BiddingOrderDetailsActivity.start(context, entity.getOrderNo(), 1);
        }
    }


    /**
     * 拨号检查
     *
     * @param entity
     */
    private void checkCanCall(OrderQuoteEntity entity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(context);
            return;
        }
        if (!TextUtils.isEmpty(entity.getTelphone())) {
            showCallDialog(entity.getTelphone());
        } else {
            ToastUtil.show(context, "无联系方式");
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

    /**
     * 拨打电话对话框
     *
     * @param number
     */
    private void showCallDialog(String number) {
        new RoundDialog.Builder(context)
                .title("确认呼叫")
                .content(number)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(number);
                    }
                })
                .show();
    }

    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }


    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */
    public static String replaceString2Star(String content, int frontNum, int endNum) {
        if (content == null || content.trim().isEmpty())
            return "";
        int len = content.length();

        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0)
            return content;

        if (frontNum + endNum >= len)
            return content;

        int beginIndex = frontNum;
        int endIndex = len - endNum;
        char[] cardChar = content.toCharArray();

        for (int j = beginIndex; j < endIndex; j++) {
            cardChar[j] = '*';
        }

        return new String(cardChar);
    }
}
